package com.rbac.interceptor;

import com.rbac.annotation.RequiresPermission;
import com.rbac.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 权限验证拦截器
 */
@Component
public class PermissionInterceptor implements HandlerInterceptor {
    
    private static final Logger logger = LoggerFactory.getLogger(PermissionInterceptor.class);
    
    @Autowired
    @Lazy
    private UserService userService;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是方法处理器，直接放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        
        // 获取方法上的权限注解
        RequiresPermission methodAnnotation = handlerMethod.getMethodAnnotation(RequiresPermission.class);
        // 获取类上的权限注解
        RequiresPermission classAnnotation = handlerMethod.getBeanType().getAnnotation(RequiresPermission.class);
        
        // 如果方法和类上都没有权限注解，直接放行
        if (methodAnnotation == null && classAnnotation == null) {
            logger.debug("方法 {} 没有权限注解，直接放行", handlerMethod.getMethod().getName());
            return true;
        }
        
        logger.debug("开始验证权限，方法: {}, 类: {}", 
            handlerMethod.getMethod().getName(), 
            handlerMethod.getBeanType().getSimpleName());
        
        // 获取当前用户的权限列表
        List<String> userPermissions = userService.getUserPermissions();
        logger.debug("用户权限列表: {}", userPermissions);
        
        if (userPermissions == null || userPermissions.isEmpty()) {
            logger.warn("用户没有权限，返回403");
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return false;
        }
        
        // 验证方法级权限
        if (methodAnnotation != null) {
            logger.debug("验证方法级权限: {}", methodAnnotation.value());
            if (!hasPermission(methodAnnotation, userPermissions)) {
                logger.warn("方法级权限验证失败: {}", methodAnnotation.value());
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                return false;
            }
        }
        
        // 验证类级权限
        if (classAnnotation != null) {
            logger.debug("验证类级权限: {}", classAnnotation.value());
            if (!hasPermission(classAnnotation, userPermissions)) {
                logger.warn("类级权限验证失败: {}", classAnnotation.value());
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                return false;
            }
        }
        
        logger.debug("权限验证通过");
        return true;
    }
    
    /**
     * 检查是否有权限
     */
    private boolean hasPermission(RequiresPermission annotation, List<String> userPermissions) {
        String[] permissions = annotation.permissions();
        String value = annotation.value();
        
        // 如果permissions数组为空，使用value
        if (permissions.length == 0) {
            permissions = new String[]{value};
        }
        
        RequiresPermission.LogicType logic = annotation.logic();
        
        if (logic == RequiresPermission.LogicType.AND) {
            // 需要所有权限
            for (String permission : permissions) {
                if (!userPermissions.contains(permission)) {
                    logger.debug("权限验证失败，缺少权限: {}", permission);
                    return false;
                }
            }
            return true;
        } else {
            // 只需要一个权限
            for (String permission : permissions) {
                if (userPermissions.contains(permission)) {
                    logger.debug("权限验证成功，拥有权限: {}", permission);
                    return true;
                }
            }
            logger.debug("权限验证失败，没有所需权限: {}", String.join(", ", permissions));
            return false;
        }
    }
} 